﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SqlSugar;
using WebApi.Common.Standard;

namespace WebApi
{
    public class DbProvider
    {
        public static SqlSugarClient GetMasterInstance()
        {
            SqlSugarClient db = new SqlSugarClient(GetMasterConnectionConfig());
            db.Ado.IsEnableLogEvent = true;
            db.Ado.LogEventStarting = (sql, pars) =>
            {
                Task t = StartLog(sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
            };
            /*
            db.QueryFilter.Add(new SqlFilterItem()
            {
                FilterValue = filterDb =>
                {
                    return new SqlFilterResult() { Sql = " IsDeleted=0" };
                },
                IsJoinQuery = false
            });
            */
            return db;
        }
        private static ConnectionConfig GetMasterConnectionConfig()
        {
            ConnectionConfig connconfig = new ConnectionConfig()
            {
                ConnectionString = ConfigExtensions.Configuration["DbConnection:MySqlConnectionString"],// "",
                DbType = DbType.MySql,
                IsAutoCloseConnection = true,
                //ConfigureExternalServices = new ConfigureExternalServices()
                //{
                //    DataInfoCacheService = new HttpRuntimeCache() //RedisCache是继承ICacheService自已实现的一个类
                //}
            };
            return connconfig;
        }
        private async static Task StartLog(string logger)
        {
            await Task.Run(() =>
            {

                StringBuilder sb = new StringBuilder();
                sb.Append("\r\n=================================================\r\n");
                sb.Append("Sql语句\r\n");
                sb.Append(logger + "\r\n");
                sb.Append(@"" + DateTime.Now + "\r\n");
                sb.Append("=================================================\r\n");

                string dir = AppDomain.CurrentDomain.BaseDirectory + ("/Logs/SysSqlLog");
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                string path = dir + "/Sql_" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                StreamWriter FileWriter = new StreamWriter(path, true, Encoding.UTF8);
                FileWriter.Write(sb.ToString());
                FileWriter.Close();
            });
        }
    }
}
